package com.sayonaragutgut.android.core;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sayonaragutgut.android.R;
import com.sayonaragutgut.android.R.id;

public final class VagasEntryAdapter extends ArrayAdapter<VagasEntry> {
	private final int vagasItemLayoutResource;
	
	public VagasEntryAdapter(final Context context, final int vagasItemLayoutResource) {
		super(context, 0);
		this.vagasItemLayoutResource = vagasItemLayoutResource;
	}
	
	@Override
	public View getView(final int position, final View convertView, final ViewGroup parent) {
		final View view = getWorkingView(convertView);
		final ViewHolder viewHolder = getViewHolder(view);
		final VagasEntry entry = getItem(position);
		
		viewHolder.tituloVagaView.setText(entry.getTituloVaga());
		viewHolder.nomeEmpresaView.setText(entry.getNomeEmpresa());
		
		int bandeiraResource = BandeiraEstadoHelper.resolveBandeiraResource(entry.getSiglaEstado());
		if (bandeiraResource != 0) viewHolder.bandeiraEstadoView.setImageResource(bandeiraResource);
		
		viewHolder.nomeCidadeView.setText(entry.getNomeCidade());
		
		return view;
	}
	
	private View getWorkingView(final View convertView) {
		View workingView = null;
		
		if (null == convertView) {
			final Context context = getContext();
			final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			workingView = inflater.inflate(vagasItemLayoutResource, null);
		} else {
			workingView = convertView;
		}
		
		return workingView;
	}
	
	private ViewHolder getViewHolder(final View workingView) {
		final Object tag = workingView.getTag();
		ViewHolder viewHolder = null;
		
		if (null == tag || !(tag instanceof ViewHolder)) {
			viewHolder = new ViewHolder();
			
			viewHolder.tituloVagaView = (TextView) workingView.findViewById(R.id.vagas_entry_tituloVaga);
			viewHolder.nomeEmpresaView = (TextView) workingView.findViewById(R.id.vagas_entry_nomeEmpresa);
			viewHolder.bandeiraEstadoView = (ImageView) workingView.findViewById(R.id.vagas_entry_bandeiraEstado);
			viewHolder.nomeCidadeView = (TextView) workingView.findViewById(R.id.vagas_entry_nomeCidade);
			
			workingView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) tag;
		}
		
		return viewHolder;
	}
	
	private static class ViewHolder {
		public TextView tituloVagaView;
		public TextView nomeEmpresaView;
		public ImageView bandeiraEstadoView;
		public TextView nomeCidadeView;
	}
}


